const { DataTypes } = require('sequelize');
const bcrypt = require('bcryptjs');

module.exports = (sequelize) => {
  const Admin = sequelize.define('Admin', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  username: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    comment: '管理员用户名'
  },
  email: {
    type: DataTypes.STRING(100),
    allowNull: true,
    unique: true,
    validate: {
      isEmail: true
    },
    comment: '邮箱地址'
  },
  phone: {
    type: DataTypes.STRING(20),
    allowNull: true,
    comment: '手机号码'
  },
  password: {
    type: DataTypes.STRING(255),
    allowNull: false,
    comment: '密码哈希'
  },
  realName: {
    type: DataTypes.STRING(50),
    allowNull: true,
    field: 'real_name',
    comment: '真实姓名'
  },
  avatar: {
    type: DataTypes.STRING(255),
    allowNull: true,
    comment: '头像URL'
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive', 'locked'),
    defaultValue: 'active',
    comment: '账户状态'
  },
  lastLoginAt: {
    type: DataTypes.DATE,
    allowNull: true,
    field: 'last_login_at',
    comment: '最后登录时间'
  },
  lastLoginIp: {
    type: DataTypes.STRING(45),
    allowNull: true,
    field: 'last_login_ip',
    comment: '最后登录IP'
  },
  loginFailCount: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    field: 'login_fail_count',
    comment: '登录失败次数'
  },
  lockedUntil: {
    type: DataTypes.DATE,
    allowNull: true,
    field: 'locked_until',
    comment: '锁定到期时间'
  },
  createdBy: {
    type: DataTypes.INTEGER,
    allowNull: true,
    field: 'created_by',
    references: {
      model: 'Admins',
      key: 'id'
    },
    comment: '创建者ID'
  },
  updatedBy: {
    type: DataTypes.INTEGER,
    allowNull: true,
    field: 'updated_by',
    references: {
      model: 'Admins',
      key: 'id'
    },
    comment: '更新者ID'
  }
}, {
  tableName: 'admins',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  hooks: {
    beforeCreate: async (admin) => {
      if (admin.password) {
        const salt = await bcrypt.genSalt(12);
        admin.password = await bcrypt.hash(admin.password, salt);
      }
    },
    beforeUpdate: async (admin) => {
      if (admin.changed('password')) {
        const salt = await bcrypt.genSalt(12);
        admin.password = await bcrypt.hash(admin.password, salt);
      }
    }
  }
});

// 实例方法：验证密码
Admin.prototype.verifyPassword = async function(password) {
  return await bcrypt.compare(password, this.password);
};

// 实例方法：检查账户是否被锁定
Admin.prototype.isLocked = function() {
  return this.status === 'locked' || 
         (this.lockedUntil && this.lockedUntil > new Date());
};

// 实例方法：增加登录失败次数
Admin.prototype.incrementLoginFails = async function() {
  this.loginFailCount += 1;
  
  // 如果失败次数达到5次，锁定账户30分钟
  if (this.loginFailCount >= 5) {
    this.status = 'locked';
    this.lockedUntil = new Date(Date.now() + 30 * 60 * 1000); // 30分钟后解锁
  }
  
  await this.save();
};

// 实例方法：重置登录失败次数
Admin.prototype.resetLoginFails = async function() {
  this.loginFailCount = 0;
  this.status = 'active';
  this.lockedUntil = null;
  await this.save();
};

// 关联关系
Admin.belongsTo(Admin, { as: 'creator', foreignKey: 'createdBy' });
Admin.belongsTo(Admin, { as: 'updater', foreignKey: 'updatedBy' });

  return Admin;
};